package com.outlandr.irc.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.LinkedList;

public class MessageManager extends Thread {

	private BufferedReader in;
	private LinkedList<String> messages = new LinkedList<String>();
	private Object monitor;
	private boolean finished = false;
	
	private MessageManager() {};

	public MessageManager(BufferedReader in, Object monitor) {
		this.in = in; 
		this.monitor = monitor;
	}
	public synchronized String getMessage() {
		if (hasMessages()) {
			return messages.removeFirst(); 
		}
		return null;
	}

	@Override
	public void run() {
		String data;
		
		try {
			while (in != null && !finished && (data = in.readLine()) != null) {
				addMessage(data);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void addMessage(String data) {
		messages.add(data);
		synchronized (monitor) {
			monitor.notifyAll();
		}
	}

	public synchronized boolean hasMessages() {
		return !messages.isEmpty();
	}

	public void finish() {
		this.finished  = true;
		
	}

}
